package com.gmrz.uaf.common;

import com.gmrz.util.Convert;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public abstract class TLVType3 {
    static final int TAG_SIZE = 2;
    static final int LENGTH_SIZE = 2;
    List<TLVSegment> tlvs;

    public TLVType3() {
        this.tlvs = Collections.synchronizedList(new ArrayList());
    }

    public void addTLVSegment(int tag, int length, byte[] data) {
        TLVSegment segment = new TLVSegment(tag, length, data);
        synchronized (this.tlvs) {
            this.tlvs.add(segment);
        }
    }

    public void addTLVSegment(int tag, byte[] data) {
        int length = data.length;
        addTLVSegment(tag, length, data);
    }

    public byte[] getValueOfTag(int tag) {
        synchronized (this.tlvs) {
            for (TLVSegment seg : this.tlvs) {
                if (tag == seg.tag) {
                    return seg.data;
                }
            }
        }
        return null;
    }

    public byte[] getTLVBytes() throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        synchronized (this.tlvs) {
            Iterator itr = this.tlvs.iterator();
            while (itr.hasNext()) {
                TLVSegment seg = (TLVSegment) itr.next();
                ByteBuffer bb = ByteBuffer.wrap(new byte[seg.length + 2 + 2]).order(ByteOrder.LITTLE_ENDIAN);
         bb.putShort((short)seg.tag).putShort((short)seg.length).put(seg.data == null ? new byte[0] : seg.data);
//                bb.put(Convert.intToByteArray(seg.tag)).put(Convert.intToByteArray(seg.length)).put(seg.data == null ? new byte[0] : seg.data);
                baos.write(bb.array());
            }
        }
        return baos.toByteArray();
    }

    private static class TLVSegment {
        int tag;
        int length;
        byte[] data;

        TLVSegment(int tag, int length, byte[] data) {
            this.tag = tag;
            this.length = length;
            this.data = data;
        }
    }

}
